﻿using System;
using System.Text;
using System.Windows.Forms;
using NoNameGoServer.Client.Commands;

namespace NoNameGoServer.Client.Gui {
    public partial class NNGSClientConversationUserControl : UserControl {
        private const int BUFFER_SIZE = 10000;
        private NNGSClient _nngsClient;

        public NNGSClient NNGSClient {
            get { return _nngsClient; }
            set {
                if (_nngsClient != null) {
                    _nngsClient.DataReceived -= NNGSClientDataReceived;
                }
                _nngsClient = value;
                if (_nngsClient != null) {
                    _nngsClient.DataReceived += NNGSClientDataReceived;
                }
            }
        }

        private void NNGSClientDataReceived(NNGSClient source, NNGSClient.DataReceivedData args) {
            MethodInvoker mi = delegate {
                StringBuilder s = new StringBuilder(_data.Text);
                for (int i = 0; i < args.Count; i++) {
                    s.Append((char)args.Buffer[i]);
                }
                int startIndex = s.Length - BUFFER_SIZE;
                if (startIndex < 0) startIndex = 0;
                int length = s.Length - startIndex;
                SetText(s.ToString(startIndex, length));
            };
            this.Invoke(mi);
        }

        public NNGSClientConversationUserControl() {
            InitializeComponent();
        }

        private void _send_Click(object sender, EventArgs e) {
            SendCommand();
        }

        private void _command_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                SendCommand();
            }
        }

        private void SendCommand() {
            try {
                RawCommand cmd = new RawCommand(string.Format("{0}\n", _command.Text));
                _command.Text = "";
                _nngsClient.EnqueueCommand(cmd);
            }
            catch (Exception ex) {
                SetText(string.Format("{0}\n{1}\n", _data.Text, ex.Message));
            }
        }

        private void SetText(string text) {
            _data.Text = text;
            _data.Select(_data.Text.Length, 0);
            _data.ScrollToCaret();
        }
    }
}
